package com.example.gestureprac.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.gestureprac.model.GestureEvent
import com.example.gestureprac.model.GestureType
import com.example.gestureprac.repository.GestureRepository
import kotlinx.coroutines.launch

/**
 * 手势ViewModel，负责处理手势相关的业务逻辑
 */
class GestureViewModel(private val repository: GestureRepository) : ViewModel() {
    
    // 私有LiveData，用于存储当前手势事件
    private val _currentGesture = MutableLiveData<GestureEvent?>(null)
    // 公开的LiveData，供UI层观察
    val currentGesture: LiveData<GestureEvent?> = _currentGesture
    
    // 私有LiveData，用于存储手势历史
    private val _gestureHistory = MutableLiveData<List<GestureEvent>>(emptyList())
    // 公开的LiveData，供UI层观察
    val gestureHistory: LiveData<List<GestureEvent>> = _gestureHistory
    
    /**
     * 处理点击事件
     */
    fun onTap(x: Float, y: Float) {
        val event = GestureEvent(GestureType.CLICK, x = x, y = y)
        _currentGesture.value = event
        saveGestureEvent(event)
    }
    
    /**
     * 处理长按事件
     */
    fun onLongPress(x: Float, y: Float) {
        val event = GestureEvent(GestureType.LONG_CLICK, x = x, y = y)
        _currentGesture.value = event
        saveGestureEvent(event)
    }
    
    /**
     * 处理双击事件
     */
    fun onDoubleTap(x: Float, y: Float) {
        val event = GestureEvent(GestureType.DOUBLE_CLICK, x = x, y = y)
        _currentGesture.value = event
        saveGestureEvent(event)
    }
    
    /**
     * 保存手势事件并更新历史记录
     */
    private fun saveGestureEvent(event: GestureEvent) {
        viewModelScope.launch {
            repository.saveGestureEvent(event)
            loadGestureHistory()
        }
    }
    
    /**
     * 加载手势历史记录
     */
    fun loadGestureHistory() {
        viewModelScope.launch {
            val history = repository.getRecentGestureEvents()
            _gestureHistory.value = history
        }
    }
}

/**
 * ViewModel工厂，用于创建GestureViewModel实例
 */
class GestureViewModelFactory(private val repository: GestureRepository) : androidx.lifecycle.ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(GestureViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return GestureViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}